<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="navbar">
      <text class="navbar-title">消息</text>
      <view class="navbar-icon">&#xe614;</view>
    </view>
    <!-- 筛选标签 -->
    <view class="filter-bar">
      <view class="filter-item active">消息列表</view>
    </view>
    <!-- 消息列表 -->
    <view class="msg-list">
      <view class="msg-item" v-for="(item, idx) in msgList" :key="idx" @click="goToChat(item)">
        <image :src="item.avatar" class="msg-avatar" v-if="item.avatar"/>
        <view v-else :class="['msg-avatar', item.iconBg]">
          <text :class="['iconfont', item.icon]"></text>
        </view>
        <view class="msg-content">
          <view class="msg-header">
            <text class="msg-name">{{ item.name }}</text>
            <text class="msg-time">{{ item.time }}</text>
          </view>
          <view class="msg-body">
            <text class="msg-text">{{ item.text }}</text>
            <view v-if="item.unread" class="msg-unread">{{ item.unread }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import chatManager from '@/utils/chat.js'
import { getRecentConversations } from '@/utils/chatStore.js'
import { fetchRecent, clearUnread } from '@/api/chat.js'

export default {
  data() {
    return {
      totalUnreadCount: 0,
      titleBlinkInterval: null, // 标题闪烁定时器
      msgList: [],
      currentUserId: ''
    }
  },

  onLoad() {
    const userInfo = uni.getStorageSync('userInfo') || {}
    this.currentUserId = userInfo.id || ''
    this.updateUnreadCounts()
    this.refreshMsgList()
    this.registerGlobalEvents()
  },

  onShow() {
    // 页面显示时更新未读消息计数
    this.updateUnreadCounts()
    this.refreshMsgList()
    
    // 停止标题闪烁并恢复正常标题
    if (this.titleBlinkInterval) {
      clearInterval(this.titleBlinkInterval)
      this.titleBlinkInterval = null
    }
    uni.setNavigationBarTitle({
      title: '消息'
    })
  },

  onUnload() {
    // 移除全局事件监听
    uni.$off('newMessage')
    uni.$off('unreadCountChanged')
    
    // 清除标题闪烁定时器
    if (this.titleBlinkInterval) {
      clearInterval(this.titleBlinkInterval)
      this.titleBlinkInterval = null
    }
  },

  methods: {
    // 注册全局事件监听
    registerGlobalEvents() {
      // 监听新消息事件
      uni.$on('newMessage', (data) => {
        // 兼容：既刷新列表，也按消息内容置顶
        if (data && data.message) {
          this.handleNewMessage(data.message)
        }
        this.refreshMsgList()
        this.updateUnreadCounts()
      })

      // 监听未读消息计数变化
      uni.$on('unreadCountChanged', (count) => {
        this.totalUnreadCount = count
      })
    },

    // 刷新最近会话列表
    refreshMsgList() {
      // 优先尝试从后端获取最近会话与未读数
      fetchRecent(this.currentUserId)
        .then(list => {
          if (Array.isArray(list) && list.length) {
            this.msgList = list.map(c => {
              const latest = c.latest || c.latestMessage || c.LatestMessage || {}
              const ts = latest.timestamp || latest.Timestamp
              const content = latest.content || latest.Content || ''
              const productId = latest.productId || latest.ProductId || ''
              return {
                avatar: c.avatar || c.Avatar || '/static/default-avatar.png',
                name: c.userName || c.UserName || `用户${c.userId || c.UserId}`,
                time: this.formatTime(ts ? (typeof ts === 'string' ? new Date(ts).getTime() : ts) : Date.now()),
                text: content,
                unread: c.unread || c.Unread || c.unreadCount || c.UnreadCount || 0,
                userId: c.userId || c.UserId,
                productId: productId,
                chatType: 'user'
              }
            })
          } else {
            // 后端无数据时降级为本地
            const convs = getRecentConversations(this.currentUserId)
            this.msgList = convs.map(c => ({
              avatar: '/static/default-avatar.png',
              name: `用户${c.userId}`,
              time: this.formatTime(c.latest.timestamp),
              text: c.latest.content,
              unread: chatManager.getUnreadCount(c.userId),
              userId: c.userId,
              productId: c.latest.productId || '',
              chatType: 'user'
            }))
          }
        })
        .catch(() => {
          // 请求失败时降级为本地
          const convs = getRecentConversations(this.currentUserId)
          this.msgList = convs.map(c => ({
            avatar: '/static/default-avatar.png',
            name: `用户${c.userId}`,
            time: this.formatTime(c.latest.timestamp),
            text: c.latest.content,
            unread: chatManager.getUnreadCount(c.userId),
            userId: c.userId,
            productId: c.latest.productId || '',
            chatType: 'user'
          }))
        })
    },

    // 处理新消息
    handleNewMessage(message) {
      // 查找对应的消息项
      const msgItem = this.msgList.find(item => item.userId === message.from)
      if (msgItem) {
        // 更新最新消息内容和时间
        msgItem.text = message.content
        msgItem.time = this.formatTime(message.timestamp)
        msgItem.unread = chatManager.getUnreadCount(message.from)
        
        // 将该消息项移到列表顶部
        const index = this.msgList.indexOf(msgItem)
        if (index > 0) {
          this.msgList.splice(index, 1)
          this.msgList.unshift(msgItem)
        }
      } else {
        // 如果是新的聊天对象，添加到列表顶部
        this.msgList.unshift({
          avatar: '/static/default-avatar.png',
          name: `用户${message.from}`,
          time: this.formatTime(message.timestamp),
          text: message.content,
          unread: 1,
          userId: message.from,
          productId: message.productId || '',
          chatType: 'user'
        })
      }
      
      // 显示新消息提示
      this.showNewMessageNotification(message)
    },
    
    // 显示新消息通知
    showNewMessageNotification(message) {
      // 显示Toast提示
      uni.showToast({
        title: `收到新消息: ${message.content.length > 10 ? message.content.substring(0, 10) + '...' : message.content}`,
        icon: 'none',
        duration: 2000
      })
      
      // 页面标题闪烁提示
      this.startTitleBlink()
      
      // 震动提示（如果设备支持）
      if (uni.vibrateShort) {
        uni.vibrateShort({
          type: 'light'
        })
      }
    },
    
    // 开始标题闪烁
    startTitleBlink() {
      // 清除之前的闪烁定时器
      if (this.titleBlinkInterval) {
        clearInterval(this.titleBlinkInterval)
      }
      
      let blinkCount = 0
      const maxBlinks = 6 // 闪烁3次（每次包含显示和隐藏）
      
      this.titleBlinkInterval = setInterval(() => {
        if (blinkCount >= maxBlinks) {
          clearInterval(this.titleBlinkInterval)
          this.titleBlinkInterval = null
          uni.setNavigationBarTitle({
            title: '消息'
          })
          return
        }
        
        const title = blinkCount % 2 === 0 ? '【新消息】消息' : '消息'
        uni.setNavigationBarTitle({
          title: title
        })
        
        blinkCount++
      }, 500) // 每500ms切换一次
    },

    // 更新未读消息计数
    updateUnreadCounts() {
      this.totalUnreadCount = chatManager.getUnreadCount()
      
      // 更新每个用户的未读消息数
      this.msgList.forEach(item => {
        if (item.chatType === 'user') {
          item.unread = chatManager.getUnreadCount(item.userId)
        }
      })
    },

    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
      
      if (messageDate.getTime() === today.getTime()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else {
        const diffDays = Math.floor((today - messageDate) / (1000 * 60 * 60 * 24))
        if (diffDays === 1) {
          return '昨天'
        } else if (diffDays < 7) {
          return `${diffDays}天前`
        } else {
          return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
        }
      }
    },

    goToChat(item) {
      // 只有用户消息才能跳转到聊天界面
      if (item.chatType === 'user') {
        // 清除该用户的未读消息
        chatManager.clearUnreadMessages(item.userId)
        item.unread = 0
        // 后端清除未读
        try { clearUnread(this.currentUserId, item.userId) } catch (e) {}
        this.updateUnreadCounts()
        
        uni.navigateTo({
          url: `/pages/chat/chat?userId=${item.userId}&userName=${item.name}&productId=${item.productId}&avatar=${encodeURIComponent(item.avatar || '')}`
        });
      } else {
        // 系统消息可以显示提示或跳转到其他页面
        uni.showToast({
          title: '系统消息',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style scoped>
.container { background: #f5f5f5; min-height: 100vh; }
.navbar { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: #fff; border-bottom: 1px solid #eee; }
.navbar-title { font-size: 20px; font-weight: bold; }
.navbar-icon { font-family: "iconfont"; font-size: 22px; color: #888; }
.filter-bar { display: flex; background: #fff; border-bottom: 1px solid #eee; }
.filter-item { padding: 12px 18px; font-size: 14px; color: #888; }
.filter-item.active { color: #FF5E5E; border-bottom: 2px solid #FF5E5E; font-weight: bold; }
.msg-list { background: #fff; }
.msg-item { display: flex; align-items: center; padding: 14px 12px; border-bottom: 1px solid #f0f0f0; }
.msg-avatar { width: 48px; height: 48px; border-radius: 50%; object-fit: cover; background: #eee; display: flex; align-items: center; justify-content: center; font-size: 22px; }
.bg-blue { background: #DBEAFE; color: #3B82F6; }
.bg-green { background: #D1FAE5; color: #10B981; }
.msg-content { flex: 1; margin-left: 12px; }
.msg-header { display: flex; justify-content: space-between; }
.msg-name { font-weight: bold; font-size: 15px; }
.msg-time { color: #bbb; font-size: 12px; }
.msg-body { display: flex; justify-content: space-between; align-items: center; }
.msg-text { color: #888; font-size: 13px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.msg-unread { background: #FF5E5E; color: #fff; border-radius: 50%; width: 20px; height: 20px; font-size: 12px; display: flex; align-items: center; justify-content: center; margin-left: 8px; }
</style>
